package com.lcj.OwnerMyBatis.sqlSession;

import com.lcj.OwnerMyBatis.config.BoundSql;
import com.lcj.OwnerMyBatis.pojo.Configuration;
import com.lcj.OwnerMyBatis.pojo.MappedStatement;
import com.lcj.OwnerMyBatis.utils.GenericTokenParser;
import com.lcj.OwnerMyBatis.utils.ParameterMapping;
import com.lcj.OwnerMyBatis.utils.ParameterMappingTokenHandler;
import com.mysql.cj.util.StringUtils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author：liuchangjun
 * @Date：2021/10/27
 */
public class SimpleExecutor implements Executor{
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InstantiationException, InvocationTargetException {
        //注册驱动，获取链接
        Connection connection = configuration.getDataSource().getConnection();
        //获取并转换sql语句，并对#{}里面的值进行解析
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

        //设置参数
        String paramterType = mappedStatement.getParamteType();
        Class<?> paramterClass = getClassType(paramterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for(int i=0 ; i <parameterMappingList.size() ; i++){
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            //反射
            Field field = paramterClass.getDeclaredField(content);
            field.setAccessible(true);
            Object o = field.get(params[0]);
            preparedStatement.setObject(i+1,0);
        }
        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        ArrayList<Object> objects = new ArrayList<>();
        //封装结果集
        while (resultSet.next()){
            Object result = resultTypeClass.newInstance();
            //取出源数据
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            for(int i=1 ; i<resultSetMetaData.getColumnCount() ; i++){
                //获取字段名
                String columnName = resultSetMetaData.getColumnName(i);
                Object object = resultSet.getObject(columnName);
                //使用反射，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName,resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(0,object);
            }
            objects.add(result);
        }

        return (List<E>) objects;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if(StringUtils.isNullOrEmpty(paramterType)){
            return null;
        }
        return Class.forName(paramterType);
    }

    /**
     * 完成#{} 使用？ 代替，解析出#{}里面的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {

        //标记处理类：配置标记解析器来完成对占位符扽解析处理工作
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("{","}",parameterMappingTokenHandler);
       //解析出来sql
        String parseSql = genericTokenParser.parse(sql);
        //解析出来的参数
        List<ParameterMapping> parameterMappingList = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql,parameterMappingList);
        return boundSql;
    }
}
